import { uid } from '@/utils';
import { useState, useEffect } from 'react';
import classNames from 'classnames';
import React, { useRef } from 'react';
import ReactDOM from 'react-dom';
import { Form, Input, Popover, Radio } from 'antd';
import { useForm } from 'antd/lib/form/Form';
import styles from './index.less';
import { Spin } from 'antd';
import { allGet } from '@/services/pc';
interface OriginInvoiceModalProps {
  container?: HTMLElement;
  visible: boolean;
  defaultIndex?: number;
  data?: any;
  onClose?: () => void;
  onSuccess: (data) => Promise<boolean>;
  destroyOnClose?: boolean;
}

const OriginInvoiceModal: React.FC<OriginInvoiceModalProps> = ({
  container = document.body,
  visible,
  data,
  onClose,
  onSuccess,
  destroyOnClose = false,
}) => {
  const [form] = useForm();

  const [submitLoading, setSubmitLoading] = useState(false);
  const [isRealNameVerified, setIsRealNameVerified] = useState(false); // 是否实名认证
  const [realNameInfo, setRealNameInfo] = useState<{ name: string; idCard: string } | null>(null); // 实名信息
  const [invoiceType, setInvoiceType] = useState('0'); // 普通/专票
  const [nameType, setNameType] = useState('0'); // 企业/个人

  // 检查实名认证状态
  useEffect(() => {
    const fetchInvoiceDetail = async () => {
      if (data.status == 0 && data.classid) {
        const params: any = {
          mod: 'invoice',
          do: 'detail',
          classid: data.classid,
          version: 'pc1.0',
        };
        try {
          const response = await allGet({ params });
          if (response.data) {
            const detailData = response.data;
            // 设置发票类型和抬头类型
            setInvoiceType(detailData.type || '0');
            setNameType(detailData.nameType || '0');
            // 回显发票信息
            form.setFieldsValue({
              invoicename: detailData.invoicename,
              invoiceid: detailData.invoiceid,
              address: detailData.address,
              mobile: detailData.mobile,
              bank: detailData.bank,
              bankaccount: detailData.bankaccount,
              email: detailData.email,
            });
          }
        } catch (error) {
          console.error('获取发票详情失败:', error);
        }
      }
    };
    const checkRealNameAuth = async () => {
      const params: any = {
        mod: 'invoice',
        do: 'add',
        version: 'pc1.0',
      };
      const response = await allGet({ params });
      // 如果是个人类型，设置默认值
      if (response.data.isverify === 1) {
        setIsRealNameVerified(true);
        const info = {
          name: response.data.realname,
          idCard: response.data.idcard,
        };
        setRealNameInfo(info);
        if (nameType === '1') {
          form.setFieldsValue({
            invoicename: response.data.realname,
            invoiceid: response.data.idcard,
          });
        }
      }
    };
    fetchInvoiceDetail();
    checkRealNameAuth();
  }, [data, form]);

  //如果已实名认证，则设置默认值
  useEffect(() => {
    if (nameType === '1' && isRealNameVerified && realNameInfo) {
      form.setFieldsValue({
        invoicename: realNameInfo.name,
        invoiceid: realNameInfo.idCard,
      });
    }
    if (nameType === '0') {
      form.setFieldsValue({
        invoicename: undefined,
        invoiceid: undefined,
      });
    }
  }, [nameType, isRealNameVerified, realNameInfo, form]);
  useEffect(() => {
    // 当选择增值税专用发票时，抬头类型只能是企业
    if (invoiceType === '1' && nameType !== '0') {
      setNameType('0');
    }
  }, [invoiceType, nameType]);
  const handleSubmit = async () => {
    if (submitLoading === true) return;
    setSubmitLoading(true);
    try {
      const values = await form.validateFields();
      const submitData = {
        ...values,
        invoiceType, // 添加发票类型
        nameType, // 添加抬头类型
      };
      if ((await onSuccess(submitData)) === false) return;
      onClose?.();
      console.log(values);
    } catch (error) {
      console.log(error);
    } finally {
      setSubmitLoading(false);
    }
  };

  if (destroyOnClose && !visible) {
    return null;
  }
  const content = (
    <div className={classNames(styles.content)} style={{ display: visible ? 'block' : 'none' }}>
      <i className={styles.mask} />
      <div className={styles.main}>
        <div className={styles.header}>申请发票</div>
        {/*         <div className={styles.detai}>
          <img loading="lazy" className={styles.img} src={data.thumb} />
          <div className={styles.right}>
            <div className={styles.title}>{data.coursename}</div>
            <div className={styles.time}>{data.payline}</div>
            <div className={styles.priceWrapper}>
              <div className={styles.filed}>
                <span className={styles.key}>实付：</span>¥{data.payed}
              </div>
              <i className={styles.line} />
              <div className={styles.filed}>
                <span className={styles.key}>发票金额：</span>
                <strong>¥{data.payed}</strong>
              </div>
            </div>
          </div>
        </div> */}
        <Form
          form={form}
          scrollToFirstError
          className={styles.form}
          labelCol={{ style: { width: 96 } }}
          labelAlign="left"
          colon={false}
          layout="horizontal"
          name="basic"
          autoComplete="off"
          validateTrigger={false}
        >
          <div className={styles.invoice}>
            <label className={styles.invoicelabel}>发票类型</label>
            <div className={styles.btns}>
              <div
                className={`${styles.btn} ${invoiceType === '0' ? styles.active : ''}`}
                onClick={() => setInvoiceType('0')}
              >
                普通发票
              </div>
              <div
                className={`${styles.btn} ${invoiceType === '1' ? styles.active : ''}`}
                onClick={() => setInvoiceType('1')}
              >
                增值税专用发票
              </div>
            </div>
          </div>
          <div className={styles.title}>
            <label className={styles.titlelabel}>抬头类型</label>
            <div className={styles.btns}>
              <div
                className={`${styles.btn} ${nameType === '0' ? styles.active : ''}`}
                onClick={() => setNameType('0')}
              >
                企业
              </div>
              {invoiceType !== '1' && (
                <div
                  className={`${styles.btn} ${nameType === '1' ? styles.active : ''}`}
                  onClick={() => setNameType('1')}
                >
                  个人
                </div>
              )}
            </div>
          </div>
          {nameType === '0' && (
            <>
              <Form.Item
                label="发票抬头"
                rules={[{ required: true, message: '请填写需要开具发票的企业名称' }]}
                name="invoicename"
              >
                <Input placeholder="填写需要开具发票的企业名称" />
              </Form.Item>
              <Form.Item
                label="税号"
                rules={[{ required: true, message: '请填写纳税人识别号' }]}
                name="invoiceid"
              >
                <Input placeholder="填写纳税人识别号" />
              </Form.Item>

              <Form.Item
                label="注册地址"
                rules={[{ required: true, message: '请填写企业注册地址' }]}
                name="address"
              >
                <Input placeholder="填写企业注册地址" />
              </Form.Item>
              <Form.Item
                label="电话"
                rules={[{ required: true, message: '请填写税务登记电话' }]}
                name="mobile"
              >
                <Input placeholder="填写税务登记电话" />
              </Form.Item>
              <Form.Item
                label="开户行"
                rules={[{ required: true, message: '请银行卡开户行' }]}
                name="bank"
              >
                <Input placeholder="银行卡开户行" />
              </Form.Item>
              <Form.Item
                label="银行帐号"
                rules={[{ required: true, message: '请填写银行卡帐号' }]}
                name="bankaccount"
              >
                <Input placeholder="填写银行卡帐号 " />
              </Form.Item>
            </>
          )}
          {nameType === '1' && (
            <>
              <Form.Item
                label="姓名"
                rules={[{ required: true, message: '填写您的姓名' }]}
                name="invoicename"
              >
                <Input placeholder="填写您的姓名 " disabled={isRealNameVerified} />
              </Form.Item>
              <Form.Item
                label="身份证"
                rules={[{ required: true, message: '请填写您的身份证号' }]}
                name="invoiceid"
              >
                <Input placeholder="填写您的身份证号 " disabled={isRealNameVerified} />
              </Form.Item>
            </>
          )}

          <Form.Item
            label="用户邮箱"
            rules={[{ required: true, type: 'email', message: '请输入邮箱号' }]}
            name="email"
          >
            <Input placeholder="输入邮箱号" />
          </Form.Item>
          {/* <Form.Item label="备注" name="remark">
            <Input.TextArea />
          </Form.Item> */}
        </Form>
        <div className={styles.footer}>
          {/*  <div className={styles.button} onClick={onClose}>
            取消
          </div> */}
          <div className={classNames(styles.button, styles.submit)} onClick={handleSubmit}>
            <Spin spinning={submitLoading} size="small" /> 提交
          </div>
        </div>
        <img
          loading="lazy"
          className={styles.close}
          src={require('./images/icon-close-two.png')}
          alt=""
          onClick={() => onClose?.()}
        />
      </div>
    </div>
  );

  return ReactDOM.createPortal(
    // 这里可以是dom元素,也可以是react组件,还可以是react节点
    content,
    // 将传入的元素/组件/节点,挂载到container下面
    container,
  );
};

const show = (options: Pick<OriginInvoiceModalProps, 'data' | 'onClose' | 'onSuccess'>) => {
  const { data = {}, onClose, onSuccess } = options || {};

  const container = document.createElement('div');
  container.setAttribute('id', uid() + '' + Date.now());
  document.body.appendChild(container);
  const handleClose = () => {
    onClose?.();
    ReactDOM.unmountComponentAtNode(container);
    document.body.removeChild(container);
  };
  ReactDOM.render(
    <OriginInvoiceModal
      data={data}
      container={container}
      visible={true}
      destroyOnClose
      onClose={handleClose}
      onSuccess={onSuccess}
    />,
    container,
  );
};

type InvoiceModalType = typeof OriginInvoiceModal & {
  show: typeof show;
};
export const InvoiceModal = OriginInvoiceModal as InvoiceModalType;
InvoiceModal.show = show;

export default InvoiceModal;
